
// import { createRouter, createWebHistory, } from 'vue-router';
import { createRouter, createWebHashHistory } from 'vue-router';
import { useUserStore } from '@/stores/user'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue')
  },
  {
    path: '/traffic-monitor',
    name: 'TrafficMonitor',
    component: () => import('@/views/TrafficMonitor.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/traffic-detail/:configId',
    name: 'TrafficDetail',
    component: () => import('@/views/TrafficDetail.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/monitor/:token',
    name: 'MonitorDetail',
    component: () => import('@/views/TrafficDetail.vue')
  },
  {
    path: '/gettoken',
    name: 'GetToken',
    component: () => import('@/views/GetToken.vue')
  },
  {
    path: '/admin',
    name: 'AdminPanel',
    component: () => import('@/views/AdminPanel.vue'),
    meta: { requiresAuth: true, requiresAdmin: true }
  }
]

const router = createRouter({
  // history: createWebHistory(),
  // routes
   history: createWebHashHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  
  // 检查是否为监控模式（通过多种方式检测）
  const isMonitorMode = 
    to.path.startsWith('/monitor/') || 
    from.path.startsWith('/monitor/') ||
    window.location.hash.includes('/monitor/') ||
    sessionStorage.getItem('isMonitorMode') === 'true'
  
  // 如果从监控页面来的，标记监控模式
  if (from.path.startsWith('/monitor/')) {
    sessionStorage.setItem('isMonitorMode', 'true')
  }
  
  // 如果要去监控页面，清除监控模式标记（允许正常访问监控页面）
  if (to.path.startsWith('/monitor/')) {
    sessionStorage.removeItem('isMonitorMode')
  }
  
  // 如果当前处于监控模式，阻止访问需要认证的页面
  if (isMonitorMode && to.meta.requiresAuth) {
    // 监控模式下不允许访问需要认证的页面，重定向到令牌获取页面
    next('/gettoken')
    return
  }
  
  // 监控模式下也不允许访问主页或系统内部页面
  if (isMonitorMode && (to.path === '/' || to.path === '/traffic-monitor' || to.path === '/login' || to.path === '/register')) {
    next('/gettoken')
    return
  }
  
  // 只有在访问需要认证的页面时才初始化认证状态
  if (to.meta.requiresAuth) {
    // 如果还没有初始化身份验证状态，先初始化
    if (!userStore.isInitialized) {
      await userStore.initializeAuth()
    }
    
    if (!userStore.isLoggedIn) {
      next('/login')
      return
    }
    
    // 检查管理员权限
    if (to.meta.requiresAdmin && !userStore.user?.isAdmin) {
      next('/traffic-monitor')
      return
    }
  }
  
  next()
})

export default router
